setwd("/Users/mihwa/Google drive/Matching_optional protocol")        
data<-read.dta("/Users/mihwa/Google drive/Matching_optional protocol/matchcedaw.dta")
attach(data)

# The following will run a caliper matching algorithm on the collapsed CEDAW data.
# data will run matching diagnostics.

matchcedaw_II <- matchit(cedawboth ~ cedawonly+ p_polity2+ trans+ lnwdi_gdpc+ wdi_gdpgr+ ciri_wecon+ ciri_wopol+ ciri_wosoc+ ucdp_type3+LINVP+ eeuro+ lame+ meast+ ssafr+ easia+ seasia+ sasia+ pacific+ caribbean, data=data, method="genetic", estimand="ATT", pop.size=200, int.seed=9)
matcheddata_II<-match.data(matchcedaw_II)
write.dta(matcheddata_II, file="matchedcedaw_II.dta")

## balance checking

covar<-data[,c("cedawonly", "p_polity2", "trans","lnwdi_gdpc","wdi_gdpgr", "ciri_wecon", "ciri_wopol", "ciri_wosoc", "ucdp_type3",
               "LINVP","eeuro", "lame", "meast", "ssafr", "easia", "seasia", "sasia", "pacific", "caribbean")]

fmla <- as.formula(paste("cedawboth~",paste(names(covar),collapse="+")))

g.weights <- GenMatch(Tr=cedawboth, X=covar, BalanceMatrix=covar, estimand="ATT",  pop.size= 200,int.seed=9)
mout.gm <-  Match(INVP, cedawboth,covar,BiasAdjust=F,Weight.matrix=g.weights, estimand="ATT")

bout.gm <- MatchBalance(fmla,match.out = mout.gm,print.level=0,ks=FALSE)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=TRUE)
bal.gm2 <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=FALSE)

bal.gm=bal.gm[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal.gm2<-bal.gm2[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal=cbind(bal.gm2,bal.gm)
bal=round(bal,3)
bal=data.frame(bal)
#colnames(bal) <- c("var", "mean_Tr","mean_Co","sdiff_pooled","pval","mean_Tr2","mean_Co2","sdiff_pooled2","pval2")

write.csv(bal,"bal_cedaw_II.csv")
